/* Copyright © Worklight Ltd. 2006-2011.  All rights reserved. */

package com.worklight.androidgap.plugin;

import java.util.Iterator;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Intent;

import com.phonegap.DroidGap;
import com.phonegap.api.PhonegapActivity;
import com.phonegap.api.Plugin;
import com.phonegap.api.PluginResult;
import com.worklight.androidgap.WLAndroidUtils;
import com.worklight.wlclient.api.WLCookieExtractor;



public class NativePage extends Plugin {
		
	public static int NATIVE_ACTIVITY_REQ_CODE = 54681;
	private Activity myactivity = null;
		
	
	public void show(String cookies, String activityClassName, String data) {
		try {
			// Set cookies from WebView
			WLCookieExtractor.cookies = cookies;
			
			Intent nativeIntent = new Intent(myactivity.getApplicationContext(), Class.forName(activityClassName));
			//data can be optional
			if (data != null && data.contains("{") && data.contains("}")) {
				nativeIntent.putExtras(createIntentFromJSONData(data));
			}
			((DroidGap)myactivity).startActivityForResult(this, nativeIntent, NATIVE_ACTIVITY_REQ_CODE);
		} catch (Exception e) {
			WLAndroidUtils.error(e.getMessage(), e);
		}
	}

	@Override
	public PluginResult execute(String action, JSONArray args, String callbackId) {
		PluginResult.Status status = PluginResult.Status.OK;
		String result = "";		
		try {
			if (action.equals("show")) {
				// data can be optional
				if (args.length() > 2) {
					this.show(args.getString(0), args.getString(1), args.getString(2));
				} else {
					this.show(args.getString(0), args.getString(1), null);
				}
			}
			return new PluginResult(status, result);
		} 
		catch (JSONException e) {
			WLAndroidUtils.error(e.getMessage(), e);
			return new PluginResult(PluginResult.Status.JSON_EXCEPTION);
		}
	}

	@Override
	public boolean isSynch(String arg0) {
		return true;
	}

	@Override
	public void setContext(PhonegapActivity activity) {
		myactivity = activity;		
	}
	
	/**
	 * Convert JSON to the extras (Intent data model) of the Intent ({@link Intent})
	 * @param jsonString
	 * @param data 
	 * @return
	 */
	@SuppressWarnings("unchecked")
	private Intent createIntentFromJSONData(String jsonString) throws JSONException {
		Intent intent = new Intent();
		JSONObject extrasJson = new JSONObject(jsonString);
		Iterator <String>iter = extrasJson.keys();
		while (iter.hasNext()) {
			String key = iter.next();
			Object obj = extrasJson.get(key);
			if (extrasJson.isNull(key)) {
				String nullValue = null;
				intent.putExtra(key, nullValue);
			} else if (obj.getClass() == Boolean.class) {
				intent.putExtra(key, (Boolean) obj);
			} else if (obj.getClass() == Byte.class) {
				intent.putExtra(key, (Byte) obj);
			} else if (obj.getClass() == Character.class) {
				intent.putExtra(key, (Character) obj);
			} else if (obj.getClass() == Double.class) {
				intent.putExtra(key, (Double) obj);
			} else if (obj.getClass() == Float.class) {
				intent.putExtra(key, (Float) obj);
			} else if (obj.getClass() == Integer.class) {
				intent.putExtra(key, (Integer) obj);
			} else if (obj.getClass() == Long.class) {
				intent.putExtra(key, (Long) obj);
			} else if (obj.getClass() == Short.class) {
				intent.putExtra(key, (Short) obj);
			} else if (obj.getClass() == String.class) {
				intent.putExtra(key, (String) obj);
			} else {
				WLAndroidUtils.debug("NAtivePage.createIntentFromJSONData: " + obj.getClass().toString() + " is not supported type.");
			}
		}
		return intent;
	}
}
